package com.cupk.services;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cupk.dtos.CreateTaskRequest;
import com.cupk.dtos.TaskDto;
import com.cupk.dtos.UpdateTaskRequest;
import com.cupk.entities.Project;
import com.cupk.entities.Task;
import com.cupk.entities.User;
import com.cupk.exceptions.ResourceNotFoundException;
import com.cupk.mapper.ProjectMapper;
import com.cupk.mapper.TaskMapper;
import com.cupk.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 任务服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TaskService {
    
    private final TaskMapper taskMapper;
    private final UserMapper userMapper;
    private final ProjectMapper projectMapper;
    
    /**
     * 获取所有任务
     */
    @Transactional(readOnly = true)
    public List<TaskDto> getAllTasks() {
        log.info("获取所有任务列表");
        return taskMapper.findAllWithDetails();
    }
    
    /**
     * 根据ID获取任务详情
     */
    @Transactional(readOnly = true)
    public TaskDto getTaskById(Long id) {
        log.info("获取任务详情，ID: {}", id);
        TaskDto task = taskMapper.findByIdWithDetails(id);
        if (task == null) {
            throw new ResourceNotFoundException("任务不存在，ID: " + id);
        }
        return task;
    }
    
    /**
     * 获取用户的任务列表
     */
    @Transactional(readOnly = true)
    public List<TaskDto> getUserTasks(String username) {
        log.info("获取用户任务列表，用户名: {}", username);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            throw new ResourceNotFoundException("用户不存在: " + username);
        }
        
        return taskMapper.findByAssigneeIdWithDetails(user.getId());
    }
    
    /**
     * 根据项目ID获取任务列表
     */
    @Transactional(readOnly = true)
    public List<TaskDto> getTasksByProject(Long projectId) {
        log.info("获取项目任务列表，项目ID: {}", projectId);
        // 验证项目是否存在
        Project project = projectMapper.selectById(projectId);
        if (project == null) {
            throw new ResourceNotFoundException("项目不存在，ID: " + projectId);
        }
        
        return taskMapper.findByProjectIdWithDetails(projectId);
    }
    
    /**
     * 创建新任务
     */
    @Transactional
    public TaskDto createTask(CreateTaskRequest request) {
        log.info("创建新任务: {}", request.getTitle());
        
        // 验证项目和用户是否存在
        Project project = projectMapper.selectById(request.getProjectId());
        if (project == null) {
            throw new ResourceNotFoundException("项目不存在，ID: " + request.getProjectId());
        }
        
        User assignee = userMapper.selectById(request.getAssigneeId());
        if (assignee == null) {
            throw new ResourceNotFoundException("用户不存在，ID: " + request.getAssigneeId());
        }
        
        Task task = new Task();
        task.setTitle(request.getTitle());
        task.setDescription(request.getDescription());
        task.setProjectId(request.getProjectId());
        task.setPriority(request.getPriority());
        task.setStatus(request.getStatus());
        task.setAssigneeId(request.getAssigneeId());
        task.setDueDate(request.getDueDate());
        task.setCreatedAt(LocalDateTime.now());
        task.setUpdatedAt(LocalDateTime.now());
        
        taskMapper.insert(task);
        
        log.info("任务创建成功，ID: {}", task.getId());
        return taskMapper.findByIdWithDetails(task.getId());
    }
    
    /**
     * 更新任务信息
     */
    @Transactional
    public TaskDto updateTask(Long id, UpdateTaskRequest request) {
        log.info("更新任务信息，ID: {}", id);
        
        Task task = taskMapper.selectById(id);
        if (task == null) {
            throw new ResourceNotFoundException("任务不存在，ID: " + id);
        }
        
        // 更新任务信息
        if (request.getTitle() != null) {
            task.setTitle(request.getTitle());
        }
        if (request.getDescription() != null) {
            task.setDescription(request.getDescription());
        }
        if (request.getProjectId() != null) {
            // 验证项目是否存在
            Project project = projectMapper.selectById(request.getProjectId());
            if (project == null) {
                throw new ResourceNotFoundException("项目不存在，ID: " + request.getProjectId());
            }
            task.setProjectId(request.getProjectId());
        }
        if (request.getPriority() != null) {
            task.setPriority(request.getPriority());
        }
        if (request.getStatus() != null) {
            task.setStatus(request.getStatus());
        }
        if (request.getAssigneeId() != null) {
            // 验证用户是否存在
            User assignee = userMapper.selectById(request.getAssigneeId());
            if (assignee == null) {
                throw new ResourceNotFoundException("用户不存在，ID: " + request.getAssigneeId());
            }
            task.setAssigneeId(request.getAssigneeId());
        }
        if (request.getDueDate() != null) {
            task.setDueDate(request.getDueDate());
        }
        
        task.setUpdatedAt(LocalDateTime.now());
        taskMapper.updateById(task);
        
        log.info("任务更新成功，ID: {}", id);
        return taskMapper.findByIdWithDetails(id);
    }
    
    /**
     * 更新任务状态
     */
    @Transactional
    public TaskDto updateTaskStatus(Long id, String status) {
        log.info("更新任务状态，ID: {}, 状态: {}", id, status);
        
        Task task = taskMapper.selectById(id);
        if (task == null) {
            throw new ResourceNotFoundException("任务不存在，ID: " + id);
        }
        
        task.setStatus(status);
        task.setUpdatedAt(LocalDateTime.now());
        taskMapper.updateById(task);
        
        log.info("任务状态更新成功，ID: {}", id);
        return taskMapper.findByIdWithDetails(id);
    }
    
    /**
     * 删除任务
     */
    @Transactional
    public void deleteTask(Long id) {
        log.info("删除任务，ID: {}", id);
        
        Task task = taskMapper.selectById(id);
        if (task == null) {
            throw new ResourceNotFoundException("任务不存在，ID: " + id);
        }
        
        taskMapper.deleteById(id);
        log.info("任务删除成功，ID: {}", id);
    }
    
    /**
     * 搜索任务
     */
    @Transactional(readOnly = true)
    public List<TaskDto> searchTasks(String keyword) {
        log.info("搜索任务，关键词: {}", keyword);
        return taskMapper.searchTasksWithDetails(keyword);
    }
    
    /**
     * 检查任务是否可访问
     */
    @Transactional(readOnly = true)
    public boolean isTaskAccessible(Long taskId, String username) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            return false;
        }
        
        // 管理员可以访问所有任务
        if ("ADMIN".equals(user.getRole())) {
            return true;
        }
        
        Task task = taskMapper.selectById(taskId);
        if (task == null) {
            return false;
        }
        
        // 检查是否为任务负责人
        return task.getAssigneeId().equals(user.getId());
    }
    
    /**
     * 检查是否为任务负责人
     */
    @Transactional(readOnly = true)
    public boolean isTaskAssignee(Long taskId, String username) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            return false;
        }
        
        Task task = taskMapper.selectById(taskId);
        if (task == null) {
            return false;
        }
        
        return task.getAssigneeId().equals(user.getId());
    }
}
